<?php
/**
 * 功能：后台商品模型控制器
 * 作者：魏安来
 * 日期：2017/01/09
 */

namespace app\index\controller;
use think\Db;
use app\index\model\GoodsModel as goodsTpye;

class GoodsModel extends Base {

	/*商品模型列表*/
	public function index() {
		//调用左侧菜单
		$menuController = new Menu();
		$menuController->sidebar();
		/*显示商品模型列表*/
		//商品模型总数
		$count = count(Db::name('goods_model')->select());
		//每页显示的条数
		$pageCount = 10;
		//当前页码
		$currentPage = request()->param('page') ? request()->param('page') : 1;
		//数据表
		$table = 'goods_model';
		//分页数据
		$modelInfo = page($count, $pageCount, $currentPage, $table, false);
		$pageHtml = page($count, $pageCount, $currentPage, $table, true);
		$this->assign('modelInfo', $modelInfo);
		$this->assign('pageHtml', $pageHtml);
		return $this->fetch();
	}

	/*添加商品模型*/
	public function add() {
		if (request()->isAjax()) {
			//接收数据
			$data = input('post.');
			//定义验证规则
            $rule = [
				'name' => 'require|min:2|unique:goods_model,name='.$data['name']
            ];

            //定义错误提示信息
            $message = [
                'name.require' => '菜单名称不能为空',
				'name.min' => '菜单名称不能少于2个字符',
				'name.unique' => '菜单名称已存在'
            ];
            $validate = new \think\Validate($rule, $message);
            $result = $validate->check($data);
            if ($result) {
            	//写入数据库
				$affectRow = Db::name('goods_model')->insert($data);
				if ($affectRow) {
					return 'succ';
				} else {
					return 'error';
				}
            } else {
            	return $this->getError();
            }
		}
		return $this->fetch();
	}

	/*商品属性列表*/
	public function attrList() {
		//调用左侧菜单
		$menuController = new Menu();
		$menuController->sidebar();
		return $this->fetch();
	}

	/*商品模型编辑*/
	public function edit() {
		$id = request()->param('id');
		$modelInfo = Db::name('goods_model')->where('id', $id)->find();
		$this->assign('id', $id);
		$this->assign('model', $modelInfo);
		if (request()->isAjax()) {
			$data['name'] = input('name');
			//定义验证规则
            $rule = [
				'name' => 'require|min:2|unique:goods_model,name='.$data['name']
            ];

            //定义错误提示信息
            $message = [
                'name.require' => '菜单名称不能为空',
				'name.min' => '菜单名称不能少于2个字符',
				'name.unique' => '菜单名称已存在'
            ];
            $validate = new \think\Validate($rule, $message);
            $result = $validate->check($data);
            if ($result) {
            	//写入数据库
				$affectRow = Db::name('goods_model')->where('id', input('id'))->update($data);
				if ($affectRow) {
					return 'succ';
				} else {
					return 'error';
				}
            } else {
            	return $this->getError();
            }
		}
		return $this->fetch();
	}

}

?>